home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / PRG / MacPerl 506 appl folder.sit / MacPerl 506 appl folder / Mac_Perl_506r1m_appl / lib / Math / BigFloat.pm next >
Text File  |  1994-12-26  |  8KB  |  298 lines

  1. package Math::BigFloat;
  2.  
  3. use Math::BigInt;
  4.  
  5. use Exporter;  # just for use to be happy
  6. @ISA = (Exporter);
  7.  
  8. %OVERLOAD = ( 
  9.                 # Anonymous subroutines:
  10. '+'    =>    sub {new BigFloat &fadd},
  11. '-'    =>    sub {new BigFloat
  12.                $_[2]? fsub($_[1],${$_[0]}) : fsub(${$_[0]},$_[1])},
  13. '<=>'    =>    sub {new BigFloat
  14.                $_[2]? fcmp($_[1],${$_[0]}) : fcmp(${$_[0]},$_[1])},
  15. 'cmp'    =>    sub {new BigFloat
  16.                $_[2]? ($_[1] cmp ${$_[0]}) : (${$_[0]} cmp $_[1])},
  17. '*'    =>    sub {new BigFloat &fmul},
  18. '/'    =>    sub {new BigFloat 
  19.                $_[2]? scalar fdiv($_[1],${$_[0]}) :
  20.              scalar fdiv(${$_[0]},$_[1])},
  21. 'neg'    =>    sub {new BigFloat &fneg},
  22. 'abs'    =>    sub {new BigFloat &fabs},
  23.  
  24. qw(
  25. ""    stringify
  26. 0+    numify)            # Order of arguments unsignificant
  27. );
  28.  
  29. sub new {
  30.   my $foo = fnorm($_[1]);
  31.   panic("Not a number initialized to BigFloat") if $foo eq "NaN";
  32.   bless ¥$foo;
  33. }
  34. sub numify { 0 + "${$_[0]}" }    # Not needed, additional overhead
  35.                 # comparing to direct compilation based on
  36.                 # stringify
  37. sub stringify {
  38.     my $n = ${$_[0]};
  39.  
  40.     $n =~ s/^¥+//;
  41.     $n =~ s/E//;
  42.  
  43.     $n =~ s/([-+]¥d+)$//;
  44.  
  45.     my $e = $1;
  46.     my $ln = length($n);
  47.  
  48.     if ($e > 0) {
  49.     $n .= "0" x $e . '.';
  50.     } elsif (abs($e) < $ln) {
  51.     substr($n, $ln + $e, 0) = '.';
  52.     } else {
  53.     $n = '.' . ("0" x (abs($e) - $ln)) . $n;
  54.     }
  55.  
  56.     # 1 while $n =~ s/(.*¥d)(¥d¥d¥d)/$1,$2/;
  57.  
  58.     return $n;
  59. }
  60.  
  61. # Arbitrary length float math package
  62. #
  63. # by Mark Biggar
  64. #
  65. # number format
  66. #   canonical strings have the form /[+-]¥d+E[+-]¥d+/
  67. #   Input values can have inbedded whitespace
  68. # Error returns
  69. #   'NaN'           An input parameter was "Not a Number" or 
  70. #                       divide by zero or sqrt of negative number
  71. # Division is computed to 
  72. #   max($div_scale,length(dividend)+length(divisor)) 
  73. #   digits by default.
  74. # Also used for default sqrt scale
  75.  
  76. $div_scale = 40;
  77.  
  78. # Rounding modes one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
  79.  
  80. $rnd_mode = 'even';
  81.  
  82. sub fadd; sub fsub; sub fmul; sub fdiv;
  83. sub fneg; sub fabs; sub fcmp;
  84. sub fround; sub ffround;
  85. sub fnorm; sub fsqrt;
  86.  
  87. #   bigfloat routines
  88. #
  89. #   fadd(NSTR, NSTR) return NSTR            addition
  90. #   fsub(NSTR, NSTR) return NSTR            subtraction
  91. #   fmul(NSTR, NSTR) return NSTR            multiplication
  92. #   fdiv(NSTR, NSTR[,SCALE]) returns NSTR   division to SCALE places
  93. #   fneg(NSTR) return NSTR                  negation
  94. #   fabs(NSTR) return NSTR                  absolute value
  95. #   fcmp(NSTR,NSTR) return CODE             compare undef,<0,=0,>0
  96. #   fround(NSTR, SCALE) return NSTR         round to SCALE digits
  97. #   ffround(NSTR, SCALE) return NSTR        round at SCALEth place
  98. #   fnorm(NSTR) return (NSTR)               normalize
  99. #   fsqrt(NSTR[, SCALE]) return NSTR        sqrt to SCALE places
  100.  
  101. # Convert a number to canonical string form.
  102. #   Takes something that looks like a number and converts it to
  103. #   the form /^[+-]¥d+E[+-]¥d+$/.
  104. sub fnorm { #(string) return fnum_str
  105.     local($_) = @_;
  106.     s/¥s+//g;                               # strip white space
  107.     if (/^([+-]?)(¥d*)(¥.(¥d*))?([Ee]([+-]?¥d+))?$/ && "$2$4" ne '') {
  108.     &norm(($1 ? "$1$2$4" : "+$2$4"),(($4 ne '') ? $6-length($4) : $6));
  109.     } else {
  110.     'NaN';
  111.     }
  112. }
  113.  
  114. # normalize number -- for internal use
  115. sub norm { #(mantissa, exponent) return fnum_str
  116.     local($_, $exp) = @_;
  117.     if ($_ eq 'NaN') {
  118.     'NaN';
  119.     } else {
  120.     s/^([+-])0+/$1/;                        # strip leading zeros
  121.     if (length($_) == 1) {
  122.         '+0E+0';
  123.     } else {
  124.         $exp += length($1) if (s/(0+)$//);  # strip trailing zeros
  125.         sprintf("%sE%+ld", $_, $exp);
  126.     }
  127.     }
  128. }
  129.  
  130. # negation
  131. sub fneg { #(fnum_str) return fnum_str
  132.     local($_) = fnorm($_[$[]);
  133.     vec($_,0,8) ^= ord('+') ^ ord('-') unless $_ eq '+0E+0'; # flip sign
  134.     s/^H/N/;
  135.     $_;
  136. }
  137.  
  138. # absolute value
  139. sub fabs { #(fnum_str) return fnum_str
  140.     local($_) = fnorm($_[$[]);
  141.     s/^-/+/;                               # mash sign
  142.     $_;
  143. }
  144.  
  145. # multiplication
  146. sub fmul { #(fnum_str, fnum_str) return fnum_str
  147.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  148.     if ($x eq 'NaN' || $y eq 'NaN') {
  149.     'NaN';
  150.     } else {
  151.     local($xm,$xe) = split('E',$x);
  152.     local($ym,$ye) = split('E',$y);
  153.     &norm(Math::BigInt::bmul($xm,$ym),$xe+$ye);
  154.     }
  155. }
  156. # addition
  157. sub fadd { #(fnum_str, fnum_str) return fnum_str
  158.     local($x,$y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  159.     if ($x eq 'NaN' || $y eq 'NaN') {
  160.     'NaN';
  161.     } else {
  162.     local($xm,$xe) = split('E',$x);
  163.     local($ym,$ye) = split('E',$y);
  164.     ($xm,$xe,$ym,$ye) = ($ym,$ye,$xm,$xe) if ($xe < $ye);
  165.     &norm(Math::BigInt::badd($ym,$xm.('0' x ($xe-$ye))),$ye);
  166.     }
  167. }
  168.  
  169. # subtraction
  170. sub fsub { #(fnum_str, fnum_str) return fnum_str
  171.     fadd($_[$[],fneg($_[$[+1]));    
  172. }
  173.  
  174. # division
  175. #   args are dividend, divisor, scale (optional)
  176. #   result has at most max(scale, length(dividend), length(divisor)) digits
  177. sub fdiv #(fnum_str, fnum_str[,scale]) return fnum_str
  178. {
  179.     local($x,$y,$scale) = (fnorm($_[$[]),fnorm($_[$[+1]),$_[$[+2]);
  180.     if ($x eq 'NaN' || $y eq 'NaN' || $y eq '+0E+0') {
  181.     'NaN';
  182.     } else {
  183.     local($xm,$xe) = split('E',$x);
  184.     local($ym,$ye) = split('E',$y);
  185.     $scale = $div_scale if (!$scale);
  186.     $scale = length($xm)-1 if (length($xm)-1 > $scale);
  187.     $scale = length($ym)-1 if (length($ym)-1 > $scale);
  188.     $scale = $scale + length($ym) - length($xm);
  189.     &norm(&round(Math::BigInt::bdiv($xm.('0' x $scale),$ym),$ym),
  190.         $xe-$ye-$scale);
  191.     }
  192. }
  193. # round int $q based on fraction $r/$base using $rnd_mode
  194. sub round { #(int_str, int_str, int_str) return int_str
  195.     local($q,$r,$base) = @_;
  196.     if ($q eq 'NaN' || $r eq 'NaN') {
  197.     'NaN';
  198.     } elsif ($rnd_mode eq 'trunc') {
  199.     $q;                         # just truncate
  200.     } else {
  201.     local($cmp) = Math::BigInt::bcmp(Math::BigInt::bmul($r,'+2'),$base);
  202.     if ( $cmp < 0 ||
  203.          ($cmp == 0 &&
  204.           ( $rnd_mode eq 'zero'                             ||
  205.            ($rnd_mode eq '-inf' && (substr($q,$[,1) eq '+')) ||
  206.            ($rnd_mode eq '+inf' && (substr($q,$[,1) eq '-')) ||
  207.            ($rnd_mode eq 'even' && $q =~ /[24680]$/)        ||
  208.            ($rnd_mode eq 'odd'  && $q =~ /[13579]$/)        )) ) {
  209.         $q;                     # round down
  210.     } else {
  211.         Math::BigInt::badd($q, ((substr($q,$[,1) eq '-') ? '-1' : '+1'));
  212.                     # round up
  213.     }
  214.     }
  215. }
  216.  
  217. # round the mantissa of $x to $scale digits
  218. sub fround { #(fnum_str, scale) return fnum_str
  219.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  220.     if ($x eq 'NaN' || $scale <= 0) {
  221.     $x;
  222.     } else {
  223.     local($xm,$xe) = split('E',$x);
  224.     if (length($xm)-1 <= $scale) {
  225.         $x;
  226.     } else {
  227.         &norm(&round(substr($xm,$[,$scale+1),
  228.              "+0".substr($xm,$[+$scale+1,1),"+10"),
  229.           $xe+length($xm)-$scale-1);
  230.     }
  231.     }
  232. }
  233. # round $x at the 10 to the $scale digit place
  234. sub ffround { #(fnum_str, scale) return fnum_str
  235.     local($x,$scale) = (fnorm($_[$[]),$_[$[+1]);
  236.     if ($x eq 'NaN') {
  237.     'NaN';
  238.     } else {
  239.     local($xm,$xe) = split('E',$x);
  240.     if ($xe >= $scale) {
  241.         $x;
  242.     } else {
  243.         $xe = length($xm)+$xe-$scale;
  244.         if ($xe < 1) {
  245.         '+0E+0';
  246.         } elsif ($xe == 1) {
  247.         &norm(&round('+0',"+0".substr($xm,$[+1,1),"+10"), $scale);
  248.         } else {
  249.         &norm(&round(substr($xm,$[,$xe),
  250.               "+0".substr($xm,$[+$xe,1),"+10"), $scale);
  251.         }
  252.     }
  253.     }
  254. }
  255.     
  256. # compare 2 values returns one of undef, <0, =0, >0
  257. #   returns undef if either or both input value are not numbers
  258. sub fcmp #(fnum_str, fnum_str) return cond_code
  259. {
  260.     local($x, $y) = (fnorm($_[$[]),fnorm($_[$[+1]));
  261.     if ($x eq "NaN" || $y eq "NaN") {
  262.     undef;
  263.     } else {
  264.     ord($y) <=> ord($x)
  265.     ||
  266.     (  local($xm,$xe,$ym,$ye) = split('E', $x."E$y"),
  267.          (($xe <=> $ye) * (substr($x,$[,1).'1')
  268.              || Math::BigInt::cmp($xm,$ym))
  269.     );
  270.     }
  271. }
  272. # square root by Newtons method.
  273. sub fsqrt { #(fnum_str[, scale]) return fnum_str
  274.     local($x, $scale) = (fnorm($_[$[]), $_[$[+1]);
  275.     if ($x eq 'NaN' || $x =~ /^-/) {
  276.     'NaN';
  277.     } elsif ($x eq '+0E+0') {
  278.     '+0E+0';
  279.     } else {
  280.     local($xm, $xe) = split('E',$x);
  281.     $scale = $div_scale if (!$scale);
  282.     $scale = length($xm)-1 if ($scale < length($xm)-1);
  283.     local($gs, $guess) = (1, sprintf("1E%+d", (length($xm)+$xe-1)/2));
  284.     while ($gs < 2*$scale) {
  285.         $guess = fmul(fadd($guess,fdiv($x,$guess,$gs*2)),".5");
  286.         $gs *= 2;
  287.     }
  288.     new BigFloat &fround($guess, $scale);
  289.     }
  290. }
  291.  
  292. 1;
  293.